package job

import (
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/text/gregex"
	"github.com/gogf/gf/util/gconv"
	"github.com/golang/glog"
	"yunAIYI/app/middleware"
	"yunAIYI/app/model/ai_jobs"
	"yunAIYI/app/model/ai_user"
	"yunAIYI/app/util"
)

type ResultInfo struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

//通过为struct属性绑定
type LayuiPage struct {
	Page  int `p:'page' json:"page"`
	Limit int `p:'limit' json:"limit"`
}
type LayiUiTable struct {
	Code  int               `json:"code"`
	Msg   string            `json:"msg"`
	Count int               `json:"count"`
	Data  []*ai_jobs.Entity `json:"data"`
}

func AddOrUpdateJobPage(r *ghttp.Request) {
	opeType := ""
	var oneJob *ai_jobs.Entity
	jobid := r.GetQueryString("id")

	if jobid == "" {
		//add
		opeType = "add"
	} else {
		//edit
		opeType = "edit"
		oneJob, _ = ai_jobs.Model.Where("id=?", jobid).One()

	}
	//glog.Info("参数 返回值:", jobid, oneJob)
	r.Response.WriteTpl("jobManager.html", gconv.Map(oneJob), g.Map{
		"type": opeType,
	})
}
func Page(r *ghttp.Request) {
	userName := r.Session.Get(middleware.SESSIONKEY)

	var page *LayuiPage

	if err := r.Parse(&page); err != nil {
		glog.Error("分页参数转struct异常:", err)
	}

	pageint := page.Page
	limit := page.Limit

	db := g.DB()
	count, _ := db.Table("ai_jobs").Count()
	var list []*ai_jobs.Entity
	var all gdb.Result
	if userName == "admin" {
		all, _ = db.Table("ai_jobs").Where("state!=?", -1).Order("id desc").Limit(limit*(pageint-1), limit).All()
		err := all.Structs(&list)
		if err != nil {
			glog.Error(err)
		}
	} else {
		all, _ = db.Table("ai_jobs").Where("add_user_phone=?", userName).And("state!=?", -1).Order("id desc").Limit(limit*(pageint-1), limit).All()
		err := all.Structs(&list)
		if err != nil {
			glog.Error(err)
		}
		for i := 0; i < len(list); i++ {
			list[i].UserToPhone = util.HidePhone(list[i].UserToPhone)
		}
	}

	t := LayiUiTable{Count: count, Msg: "", Code: 0, Data: list}
	r.Response.Write(t)
}
func RunOne(r *ghttp.Request) {
	id := r.GetString("id")

	//state =1表示任务有效         status=0未执行
	all, _ := ai_jobs.Model.Where("id=?", id).All()
	SendIndex(all)

	r.Response.Write("success")
}
func DeleteJob(r *ghttp.Request) {
	status := "fail"
	id := r.GetString("id")
	entity, _ := ai_jobs.Model.Where("id=?", id).One()

	entity.State = -1
	_, err := entity.Update()
	if err != nil {
		glog.Error(err)
	} else {
		status = "success"
	}
	r.Response.Write(status)
}
func ChangeState(r *ghttp.Request) {
	id := r.GetString("id")
	state := r.GetInt("state")
	if state == 0 {
		state = 1
	} else if state == 1 {
		state = 0
	}
	entity, _ := ai_jobs.Model.Where("id=?", id).One()
	entity.State = state
	_, err := entity.Update()
	status := "fail"
	if err != nil {
		glog.Error(err)
	} else {
		status = "success"

	}
	r.Response.Write(status)
}

func AddOne(r *ghttp.Request) {
	userName := r.Session.Get(middleware.SESSIONKEY)

	id := r.GetString("id")

	user_from_name := r.GetString("user_from_name")
	time := r.GetString("time")
	user_to_name := r.GetString("user_to_name")
	user_to_phone := r.GetString("user_to_phone")
	smstype := r.GetInt("smstype")

	resultInfo := ResultInfo{}
	//电话号码校验
	isphone := gregex.IsMatchString(`^(1[3|4|5|8][0-9]\d{4,8})$`, user_to_phone)
	if !isphone {
		resultInfo.Code = "fail"
		resultInfo.Message = " 收信人电话号码格式不准确!"
		r.Response.WriteExit(resultInfo)
	}
	istime := gregex.IsMatchString(`^([01]\d|2[01234]):([0-5]\d|60)$`, time)

	if !istime {
		resultInfo.Code = "fail"
		resultInfo.Message = " 时间格式不准确!"
		r.Response.WriteExit(resultInfo)
	}

	if id == "" {
		//add

		//普通会员最多3个任务
		one, _ := ai_user.Model.Where("phone=?", userName).One()
		usertype := one.Type
		size, _ := ai_jobs.Model.Where("add_user_phone=?", userName).And("state=?", 1).Count()

		if usertype == 0 && size >= 3 {
			glog.Info("已经到3个任务了  不许添加了")
			resultInfo.Code = "fail"
			resultInfo.Message = "普通会员最多只能添加3个任务,请在个人中心升级您的账号!"
		} else {
			entity := &ai_jobs.Entity{UserFromName: user_from_name,
				Time:       time,
				UserToName: user_to_name, UserToPhone: user_to_phone, State: 1, AddUserPhone: gconv.String(userName), Smstype: smstype}

			e, err := entity.Save()
			if err != nil {
				glog.Error(err)
				resultInfo.Code = "fail"
				resultInfo.Message = err.Error()
			} else {
				resultInfo.Code = "success"
				resultInfo.Message = ""
				insertid, _ := e.LastInsertId()
				id = gconv.String(insertid)
			}
		}

	} else {
		//edit
		entity, _ := ai_jobs.Model.Where("id=?", id).One()
		entity.UserToPhone = user_to_phone
		entity.UserFromName = user_from_name
		entity.UserToName = user_to_name
		entity.Time = time
		entity.Smstype = smstype

		entity.Update()

		resultInfo.Code = "success"
	}
	updateLocation(id)
	r.Response.Write(resultInfo)

}

func updateLocation(id string) {
	//启动一个协程更新phone归属地
	go func(id string) {
		glog.Info("启动一个协程更新phone归属地:", id)
		entity, _ := ai_jobs.FindOne("id=?", id)
		info := util.GetPhoneInfo(entity.UserToPhone)
		entity.Location = info
		entity.Update()

	}(id)
	go func() {
		entities, e := ai_jobs.FindAll(" (location is null  ) or (location = ?) ", "")
		glog.Info("启动一个协程更新phone归属地为空的数据,数量:", len(entities))

		if e != nil {
			glog.Error(e)
		}
		if len(entities) > 0 {
			for i := 0; i < len(entities); i++ {
				entities[i].Location = util.GetPhoneInfo(entities[i].UserToPhone)
				entities[i].Update()
			}
		} else {
			glog.Info("未检测到phone归属地为空的数据")

		}
	}()
}
